'use strict';

const path = require('path');
const fs = require('fs');
const Controller = require('egg').Controller;

class UploadController extends Controller {
  async getUploadPage(ctx) {
    await ctx.render('upload.nj');
  }

  async saveUploadFiles(ctx) {
    // https://eggjs.org/zh-cn/basics/controller.html#%E8%8E%B7%E5%8F%96%E4%B8%8A%E4%BC%A0%E7%9A%84%E6%96%87%E4%BB%B6
    const getFile = ctx.request.files[0];
    const file = fs.readFileSync(getFile.filepath);
    fs.writeFileSync(path.resolve(__dirname, '../public/upload', getFile.filename), file);
    ctx.status = 200;
    ctx.body = '上传成功' + getFile.filename;
    fs.unlink(getFile.filepath, function(err) {
      if (err) {
        console.log('删除内存文件失败');
      }
    });
  }
}

module.exports = UploadController;
